package com.pactera.madp.cp.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.common.core.exception.CheckedException;
import com.pactera.madp.cp.api.entity.ContactFieldPivotEntity;
import com.pactera.madp.cp.api.vo.ContactFieldVO;
import com.pactera.madp.cp.api.entity.ContactFieldEntity;
import com.pactera.madp.cp.api.dto.contactfield.ContactFieldDto;
import com.pactera.madp.cp.api.dto.contactfield.BatchUpdateContactFieldDto;
import com.pactera.madp.cp.api.entity.ContactFieldTypeEntity;
import com.pactera.madp.cp.api.page.SubPage;
import com.pactera.madp.cp.common.util.PinyinUtil;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.mapper.ContactFieldMapper;
import com.pactera.madp.cp.service.ContactFieldTypeService;
import com.pactera.madp.cp.service.IContactFieldService;
import com.pactera.madp.cp.service.IWorkContactFieldPivotService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhaojinjian
 * @ClassName contactFieldServiceImpl.java
 * @Description TODO
 * @createTime 2020/12/15 11:41
 */
@Service
public class ContactFieldServiceImpl extends ServiceImpl<ContactFieldMapper, ContactFieldEntity> implements IContactFieldService {

    @Autowired
    private ContactFieldTypeService contactFieldTypeService;
    @Autowired
    private IWorkContactFieldPivotService contactFieldPivotService;

    /**
     * @description 获取客户列表筛选 -- 用户画像
     * @author zhaojinjian
     * @createTime 2020/12/30 17:23
     */
    @Override
    public JSONArray getPortrait(Integer fieldId, String name) {
        QueryWrapper<ContactFieldEntity> contactFieldWrapper = new QueryWrapper<>();
        contactFieldWrapper.eq("corp_id", CorpContextHolder.getCorpId());
        contactFieldWrapper.eq("status", 1);
        if (fieldId != null) {
            contactFieldWrapper.eq("id", fieldId);
        }
        if (name != null && !name.isEmpty()) {
            contactFieldWrapper.eq("name", name);
        }
        List<ContactFieldEntity> contactFieldList = this.list(contactFieldWrapper);
        JSONArray result = new JSONArray();

        JSONObject jsonObject0 = new JSONObject();
        jsonObject0.put("fieldId", 0);
        jsonObject0.put("name", "全部");
        jsonObject0.put("type", "0");
        jsonObject0.put("typeText", "");
        jsonObject0.put("options", Collections.emptyList());
        result.add(jsonObject0);

        if (contactFieldList != null && contactFieldList.size() > 0) {
            contactFieldList.forEach(item -> {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("fieldId", item.getId());
                jsonObject.put("name", item.getLabel());
                jsonObject.put("type", item.getType());
                ContactFieldTypeEntity one = contactFieldTypeService.getOne(Wrappers.<ContactFieldTypeEntity>lambdaQuery()
                        .eq(ContactFieldTypeEntity::getId, item.getType()));
                jsonObject.put("typeText", one.getCn());
                jsonObject.put("options", JSONArray.parse(item.getOptions()));
                result.add(jsonObject);
            });
        }
        return result;
    }

    @Override
    public List<ContactFieldEntity> getContactFieldList(List<Integer> fieidIds) {
        QueryWrapper<ContactFieldEntity> contactFieldWrapper = new QueryWrapper<>();
        contactFieldWrapper.in("id", fieidIds);
        contactFieldWrapper.eq("corp_id",CorpContextHolder.getCorpId());
//        contactFieldWrapper.isNull("deleted_at");
        List<ContactFieldEntity> contactFieldEntityList = this.list(contactFieldWrapper);
        List<ContactFieldEntity> contactFieldEntityList1 = new ArrayList<ContactFieldEntity>();
        return contactFieldEntityList1;
    }

    /**
     * @description 获取高级属性详细
     * @author zhaojinjian
     * @createTime 2020/12/15 11:49
     */
    @Override
    public ContactFieldVO getContactFieldInfo(Integer fieldId) {
        ContactFieldEntity contactFieldEntity = getOne(Wrappers.<ContactFieldEntity>lambdaQuery()
                .eq(ContactFieldEntity::getId,fieldId)
                .eq(ContactFieldEntity::getCorpId,CorpContextHolder.getCorpId()));
        if (contactFieldEntity != null) {
            ContactFieldTypeEntity one = contactFieldTypeService.getOne(Wrappers.<ContactFieldTypeEntity>lambdaQuery()
                    .eq(ContactFieldTypeEntity::getId, contactFieldEntity.getType()));
            ContactFieldVO vo = new ContactFieldVO();
            BeanUtils.copyProperties(contactFieldEntity,vo);
            if (Integer.parseInt(vo.getType()) <10){
                vo.setType("0"+vo.getType());
            }
            vo.setTypeCn(one.getCn());
            vo.setTypeEn(one.getEn());
            return vo;
        }
        return new ContactFieldVO();
    }

    /**
     * @description 获取高级属性的集合
     * @author zhaojinjian
     * @createTime 2020/12/15 16:32
     * @return
     */
    @Override
    public Page<List<ContactFieldEntity>> getContactFieldList(Integer status, Page page) {
        QueryWrapper<ContactFieldEntity> contactFieldWrapper = new QueryWrapper<>();
        contactFieldWrapper.select("id,name,label,type,options,`order`,status,is_sys").orderByDesc("`order`").orderByDesc("create_time");
//        contactFieldWrapper.isNull("deleted_at");
        if(status != null && status < 2){
            contactFieldWrapper.eq("status", status);
        }
        contactFieldWrapper.eq("corp_id",CorpContextHolder.getCorpId());
//        Page<ContactFieldEntity> pages = new Page<>(page, perPage);
        page = (Page<ContactFieldEntity>) this.baseMapper.selectPage(page, contactFieldWrapper);

        List<ContactFieldEntity> contactFieldEntities = page.getRecords();
        if (contactFieldEntities != null) {
            List<ContactFieldEntity> voList = new ArrayList<>();
            contactFieldEntities.forEach(item -> {
                ContactFieldTypeEntity one = contactFieldTypeService.getOne(Wrappers.<ContactFieldTypeEntity>lambdaQuery().eq(ContactFieldTypeEntity::getId, item.getType()));
//                item.setTypeText(TypeEnum.getTypeByCode(item.getType()));
                item.setTypeCn(one.getCn());
                item.setTypeEn(one.getEn());
                if (Integer.parseInt(item.getType()) < 10){
                    item.setType("0"+item.getType());
                }

                voList.add(item);
            });
            Page subPage = new SubPage();
            subPage.setRecords(voList);
            subPage.setCurrent(page.getCurrent());
            subPage.setSize(page.getSize());
            subPage.setTotal(page.getTotal());
            return subPage;
        }
        return new SubPage();
    }

    /**
     * @description 删除高级属性
     * @author zhaojinjian
     * @createTime 2020/12/15 16:39
     */
    @Override
    public boolean deleteContactField(Integer fieldId) {
        if (fieldId == null) {
            throw new CheckedException("fieldId不能为空");
        }
        ContactFieldEntity one = getOne(Wrappers.<ContactFieldEntity>lambdaQuery().eq(ContactFieldEntity::getId, fieldId));
        if (one.getIsSys() == 1){
            throw new CheckedException("系统属性不允许删除");
        }
        ContactFieldEntity contactField = new ContactFieldEntity();
        contactField.setId(fieldId);
        contactField.setCreateTime(LocalDateTime.now());
        List<ContactFieldPivotEntity> list = contactFieldPivotService.list(Wrappers.<ContactFieldPivotEntity>lambdaQuery().eq(ContactFieldPivotEntity::getContactFieldId, fieldId));
        if (!list.isEmpty()){
            throw new CheckedException("当前属性已被引用");
        }
        return removeById(contactField);
    }

    /**
     * @description 修改高级属性的状态
     * @author zhaojinjian
     * @createTime 2020/12/15 16:52
     */
    @Override
    public boolean updateStatus(Integer fieldId, Integer status) {
        ContactFieldEntity entity = new ContactFieldEntity();
        entity.setId(fieldId);
        entity.setStatus(status);
        return this.updateById(entity);
    }

    /**
     * @description 高级属性新增
     * @author zhaojinjian
     * @createTime 2020/12/16 11:40
     */
    @Override
    public boolean insertContactField(ContactFieldDto parem) {
        ContactFieldEntity one = getOne(Wrappers.<ContactFieldEntity>lambdaQuery().eq(ContactFieldEntity::getLabel, parem.getLabel()).eq(ContactFieldEntity::getCorpId,CorpContextHolder.getCorpId()));
        if (one != null){
            throw new CheckedException("字段名称不能重复");
        }
        ContactFieldEntity contactFieldEntity = new ContactFieldEntity();
        contactFieldEntity.setType(String.valueOf(parem.getType()));
        contactFieldEntity.setCreateTime(LocalDateTime.now());
        contactFieldEntity.setIsSys(0);
        contactFieldEntity.setLabel(parem.getLabel());
        contactFieldEntity.setName(PinyinUtil.getPinyin(parem.getLabel(), ""));
        //这里参考前端用中文逗号分隔
        contactFieldEntity.setOptions(parem.getOptions());
        contactFieldEntity.setOrder(parem.getOrder());
        contactFieldEntity.setStatus(parem.getStatus());
        contactFieldEntity.setCorpId(CorpContextHolder.getCorpId());
        return this.baseMapper.insert(contactFieldEntity) == 1 ;
    }

    /**
     * @description 修改高级属性
     * @author zhaojinjian
     * @createTime 2020/12/16 11:46
     * @param parem
     */
    @Override
    public boolean updateContactField(ContactFieldDto parem) {

        ContactFieldEntity contactFieldEntity = baseMapper.selectById(parem.getId());
        if (contactFieldEntity == null) {
            //TODO 当前属性不存在
            throw new CheckedException("当前属性不存在");
        }
        if (contactFieldEntity.getIsSys() == 1){
            throw new CheckedException("系统属性不允许修改");
        }
        contactFieldEntity.setId(parem.getId());
        contactFieldEntity.setType(String.valueOf(parem.getType()));
        contactFieldEntity.setUpdateTime(LocalDateTime.now());
        if (contactFieldEntity.getIsSys() == 0) {
            contactFieldEntity.setLabel(parem.getLabel());
//            contactFieldEntity.setName(PinyinUtil.getPinyin(parem.getLabel(), ""));
        }
        //这里参考前端用中文逗号分隔
        contactFieldEntity.setOptions(parem.getOptions());
        contactFieldEntity.setOrder(parem.getOrder());
        contactFieldEntity.setStatus(parem.getStatus());
        return this.updateById(contactFieldEntity);
    }

    @Override
    public boolean updateMultipleContactField(List<ContactFieldEntity> list) {
        return this.updateBatchById(list);
    }

    /**
     * @description 批量修改高级属性
     * @author zhaojinjian
     * @createTime 2020/12/16 11:56
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean BatchUpdateContactField(BatchUpdateContactFieldDto parem) {
        boolean result = false;
        if (parem.getUpdate() != null && parem.getUpdate().size() > 0) {
            List<Integer> fieldId = parem.getUpdate().stream().map(ContactFieldDto::getId).collect(Collectors.toList());
            List<ContactFieldEntity> list = this.baseMapper.selectBatchIds(fieldId);
            list.forEach(contactFieldEntity -> {
                Optional<ContactFieldDto> model = parem.getUpdate().stream().filter(c -> c.getId() == contactFieldEntity.getId()).findAny();
                ContactFieldDto item = model.get();

                contactFieldEntity.setId(item.getId());
                contactFieldEntity.setType(String.valueOf(item.getType()));
                contactFieldEntity.setUpdateTime(LocalDateTime.now());
                if (contactFieldEntity.getIsSys() == 0) {
                    contactFieldEntity.setLabel(item.getLabel());
//                    contactFieldEntity.setName(PinyinUtil.getPinyin(item.getLabel(), ""));
                }
                //这里参考前端用中文逗号分隔
                contactFieldEntity.setOptions(item.getOptions());
                contactFieldEntity.setOrder(item.getOrder());
                contactFieldEntity.setStatus(item.getStatus());

            });
            result = this.updateBatchById(list);
        } else {
            //TODO 没有修改数据
        }
        if (parem.getDestroy() != null && parem.getDestroy().size() > 0) {
            List<ContactFieldEntity> deleteList = new ArrayList<>();
            parem.getDestroy().forEach(id -> {
                ContactFieldEntity deleteModel = new ContactFieldEntity();
                ContactFieldEntity fieldEntity = getOne(Wrappers.<ContactFieldEntity>lambdaQuery()
                        .eq(ContactFieldEntity::getId, id));
                if ( fieldEntity.getIsSys() != 1){
                    deleteModel.setId(id);
                    deleteModel.setDelFlag(1);
                    deleteList.add(deleteModel);
                }
            });
            result = this.updateBatchById(deleteList);
        }
        return result;
    }
}
